<template>
  <!-- <Header title="成渝联动 畅耍无忧" :back="true" /> -->
  <!-- <img class="cart_bg" src="@/assets/images/index/cart_bg.png" alt=""> -->
  <div class="coupon" ref="scrollYEle">
    <van-tabs
        sticky
        animated
        class="van-tabs"
        v-model:active="active"
        @click-tab="onClickTab"
    >
      <van-tab title="券中心">
        <van-pull-refresh
            class="scenic_list"
            v-model="loading"
            @refresh="onRefresh"
            immediate-check="false"
        >
          <van-list
              v-if="couponCenterList.length"
              v-model:loading="loadingCenterList"
              v-model:error="errCenterList"
              :finished="finishedCenterList"
              finished-text="没有更多了"
              error-text="出错了，点击重试"
              @load="()=>{onClickTab(false)}"
          >

            <CouponCenterList
                v-if="couponCenterList.length"
                :couponlists="couponCenterList"
                type="center"
            />
            <div v-else>
              <div class="none" v-if="!loading">
                <img
                    class="none_img"
                    src="@/assets/images/index/none1.png"
                    alt=""
                />
                <span>暂无优惠券</span>
                <div class="btn" @click="() => router.push('/')">去逛逛</div>
              </div>
              <div v-else>
                <van-skeleton :row="20"></van-skeleton>
              </div>

            </div>
          </van-list>
        </van-pull-refresh>
      </van-tab>
      <van-tab title="我的优惠券">
        <coupon-order></coupon-order>
      </van-tab>


    </van-tabs>
  </div>
</template>
<script setup>
import {onActivated, ref} from 'vue'
import Couponlist from './components/List.vue'
// import Header from "@/components/header/Header.vue";
import api from '@/api/index.js'
import {showToast} from 'vant'
import {onBeforeRouteLeave, useRoute, useRouter} from 'vue-router'
import {determineNeedSaveKeepALive} from '@/utils/routerKeepALive.js'
import {useSocket} from '@/hooks/useQRSocket.js'
import CouponCenterList from "@/views/coupon/components/CouponCenterList.vue";
import CouponOrder from "@/views/order/CouponOrder.vue";
import {getCurrentInstance} from 'vue'
import {addRouteCache, deleteRuteCache, userStore} from "@/stores/user.js";

const route = useRoute()
const router = useRouter()
const couponlists = ref([])
const couponCenterList = ref([])
const couponlistshotel = ref([])
const couponlistshotpot = ref([])
const active = ref(0)
const loading = ref(false)
const dataparams = ref({
  pageNum: 1
})
const ins = getCurrentInstance()


defineOptions({

  name: 'couponList',
})

const {socketClose} = useSocket()


const scrollYEle = ref(null)
let scrollTop = 0
onBeforeRouteLeave((to, from) => {
  const needSaveRoute = ['scenicOrderDetail']
  scrollTop = scrollYEle.value.scrollTop ?? 0
  determineNeedSaveKeepALive(to, from, needSaveRoute, 'coupon')
  socketClose && socketClose()
})
onActivated(() => {
  const scrollElement = scrollYEle.value
  scrollElement?.scrollTo({top: scrollTop || 0, behavior: 'instant'})
})

const loadingCenterList = ref(false)
const finishedCenterList = ref(false)
const errCenterList = ref(false)


const loadingCouponList = ref(false)
const finishedCouponListList = ref(false)
const errCouponListList = ref(false)
const onRefresh = () => {
  setTimeout(() => {
    // 执行其他操作
    onClickTab(dataparams.value)
    // if (active.value===1 && couponlists.value.length > 0 || active.value===0 && couponCenterList.value.length > 0) {
    //   showToast('刷新成功')
    // } else {
    //   showToast('暂无优惠券信息')
    // }

    loading.value = false
  }, 500)
}


// 更具票夹类型获取票夹信息
function onClickTab(refresh = true) {
  if (refresh) {
    dataparams.value.pageNum = 1
    couponCenterList.value = []
    couponlists.value = []
  }
  loading.value = true

  if (active.value === 1) {
    // loadingCouponList.value=true
    // dataparams.value = {
    //   kindId: 0,
    //   pageNum: dataparams.value.pageNum,
    //   pageSize: 10,
    // }
    // api
    //   .getticketList(dataparams.value)
    //   .then((res) => {
    //     if (res.code == 200) {
    //       res.data.list.forEach((item) => {
    //         item.showTicket = true
    //       })
    //       couponlists.value = [
    //           ...couponlists.value,
    //           ...res.data.list,
    //
    //       ]
    //       finishedCouponListList.value = res.data.totalPage<=res.data.currPage
    //       dataparams.value.pageNum++
    //     }
    //   })
    //   .finally(() => {
    //     loading.value=false
    //     loadingCouponList.value=false
    //   }).catch(()=>{
    //     errCouponListList.value=true
    // })
  } else if (active.value === 0) {
    loadingCenterList.value = true
    dataparams.value = {
      // kindId: 0,
      pageNum: dataparams.value.pageNum,
      pageSize: 10,
    }
    api.getCouponList(dataparams.value).then((res) => {
      if (res.code == 200) {
        res.data.list.forEach((item) => {
          item.showTicket = true
        })
        finishedCenterList.value = res.data.totalPage <= res.data.currPage
        couponCenterList.value = [
          ...couponCenterList.value,
          ...res.data.list
        ]
        errCenterList.value = false
        dataparams.value.pageNum++
      }
    }).finally(() => {

      loading.value = false
      loadingCenterList.value = false

    }).catch(() => {

      errCenterList.value = true
    })

  } else if (active.value == 2) {
    dataparams.value = {
      kindId: 3,
      pageNum: 1,
      pageSize: 999,
    }
    api.getticketList(dataparams.value).then((res) => {
      if (res.code == 200) {
        res.data.list.forEach((item) => {
          item.showTicket = true
        })
        couponlistshotpot.value = res.data.list
      }
    }).finally(() => {
      loading.value = false

    })
  }
}

const initCoupon = () => {
  const type = route.query.type
  const openId = route.query.id
  if (type === 'hotPot') {
    active.value = 2
  }
  onClickTab()
  return {openId}
}
const {openId} = initCoupon()

const user = userStore()
onBeforeRouteLeave((to, from) => {
  console.log('user.keepAliveInclude', user.keepAliveInclude)
  const name = from.name

  if (!["couponDetail", "activityOrderDetail"].includes(to.name)) {

    deleteRuteCache(name)

  } else {

    addRouteCache(name)
  }

  console.log('user.keepAliveInclude', user.keepAliveInclude)
  console.log('to', to)
  console.log('from', from)
})
</script>
<style lang="scss" scoped>
.coupon {
  background: #f9f8f3;
  height: 100%;
  overflow-y: auto;
}

:deep(.van-tabs__line) {
  height: 0.5rem;
  background: linear-gradient(236deg, #ece3aa 0%, #45c89a 100%);
}

.none {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 39rem;

  .none_img {
    width: 6rem;
    margin: 14.4rem 0 1rem 0;
  }

  span {
    font-size: 1.4rem;
    color: #666666;
  }
}

.btn {
  width: 108px;
  height: 38px;
  margin: auto;
  border-radius: 5px;
  background: rgba(79, 172, 145, 1);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}
</style>
